<script lang="ts">
  import { routeTo } from '@service/navigate';
  import type { Unsubscriber } from "svelte/store";
  import { object, string, number, type Asserts } from "yup";
  import { isSigned$ } from "@entity/User";
  import { countDown } from "@store/countdown";
  import { sendCodeAtSignIn, signIn } from "@service/auth";
  const validateSchema = object({
    mobile: string()
      .matches(/^[1][3,4,5,7,8][0-9]{9}$/, "手机格式错误")
      .required("请输入手机号码"),
    code: string()
      .matches(/^[0-9]{4}$/, "4位数字")
      .required("请输入验证码"),
  });
  const SendCodeSchema = validateSchema.pick(["mobile"]);
  const SignInSchema = validateSchema;

  let _errors: Record<string, string> = {};
  let _validateSuccess = true;
  let sendingCode = false;
  let countDownVal = 0;
  let unsub: Unsubscriber;
  let mobile = "";
  let code = "";

  async function handleSendCode() {
    try {
      await SendCodeSchema.validate({ mobile }, { abortEarly: false });
      _errors = {};
      _validateSuccess = true;
    } catch (err: any) {
      console.error(" validate err=>", err);
      if (err.inner) {
        _errors = err.inner.reduce((acc, err) => {
          return { ...acc, [err.path]: err.message };
        }, {});
      }
      _validateSuccess = false;
    }

    if (_validateSuccess) {
      unsub = countDown(1, 60, (v: number) => {
        countDownVal = v;
        sendingCode = countDownVal > 0;
        if (!sendingCode) {
          unsub = undefined;
        }
      });
      await sendCodeAtSignIn(mobile);
    }
  }

  async function handleActiviate() {
    console.log('_validateSuccess')
    try {
      await SignInSchema.validate({ mobile, code }, { abortEarly: false });
      _errors = {};
      _validateSuccess = true;
    } catch (err: any) {
      console.error(" validate err=>", err);
      if (err.inner) {
        _errors = err.inner.reduce((acc, err) => {
          return { ...acc, [err.path]: err.message };
        }, {});
      }
      _validateSuccess = false;
    }

    if (_validateSuccess) {
      if (unsub) {
        unsub();
        sendingCode = false;
        unsub = undefined;
      }

      await signIn(mobile, code)
    }
  }

  $: {
    if ($isSigned$) {
      routeTo("/");
    }
  }
</script>

<div class="h-full pt-8">
    <div class="relative rounded-lg shadow bg-gray-700 w-96 m-auto">
        <div class="flex justify-end p-2">
            <!-- <button type="button" class="text-gray-400 bg-transparent rounded-lg text-sm p-1.5 ml-auto inline-flex items-center hover:bg-gray-800 hover:text-white" >
                <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg>  
            </button> -->
        </div>
        <div class="px-6 pb-4 space-y-6 lg:px-8 sm:pb-6 xl:pb-8">
            <h3 class="text-xl font-medium ">欢迎回来</h3>
            <div>
                <label for="mobile" class="block mb-2 text-sm font-medium text-gray-300">手机号码</label>
                <div class="flex-field flex-row">
                    <input type="text" name="mobile" id="mobile" bind:value={mobile} maxlength="11"  class="modal-input" />
                    <div class="flex-start-box w-48 pl-2.5 py-2.5"><span class="error" class:hidden={!_errors.mobile}>{_errors.mobile}</span></div>
                </div>
            </div>
            <div>
                <label for="code" class="block mb-2 text-sm font-medium text-gray-300">验证码</label>
                <div class="flex-field flex-row">
                    <input type="text" name="code" id="code" bind:value={code}   maxlength="4"  class="modal-input" />
                    {#if sendingCode }
                        <div class="flex-start-box w-48 pl-2.5 py-2.5 text-gray-500">{countDownVal}秒</div>
                    {:else}
                        <button class="flex-start-box w-48 pl-2.5 py-2.5" on:click={handleSendCode}>获取验证码</button>
                    {/if}
                </div>
                <div class="flex-start-box mt-2 h-4 flex-row justify-start"><span class="error" class:hidden={!_errors.code}>{_errors.code}</span></div>
            </div>
            <!-- <div class="flex justify-between">
                <div class="flex items-start">
                    <div class="flex items-center h-5">
                        <input id="remember" aria-describedby="remember" type="checkbox" class="w-4 h-4 rounded border  focus:ring-3 bg-gray-600 border-gray-500 focus:ring-blue-600 ring-offset-gray-800" required>
                    </div>
                    <div class="ml-3 text-sm">
                    <label for="remember" class="font-medium text-gray-300">Remember me</label>
                    </div>
                </div>
                <a class="text-sm hover:underline text-blue-500">Lost Password?</a>
            </div> -->
            <button class="w-full modal-confirm-button" on:click={handleActiviate}>快速登录</button>
            <!-- <div class="text-sm font-medium text-gray-300">
                Not registered? <a  class="hover:underline text-blue-500">Create account</a>
            </div> -->
        </div>
    </div>
</div>